import request from './request';
import { message } from 'antd';
import { ApiResponse, TaskResult, OutpaintingParams } from './types';

/**
 * 上传文件
 */
export async function uploadFile(file: File) {
  const uri = '/file/upload';
  try {
    const formData = new FormData();
    formData.append('file', file);

    const res = await request.post(uri, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传结果:', res);
    return res.data;
  } catch (error) {
    console.error('上传错误:', error);
    throw error;
  }
}



/**
 * 根据task_id获得生成的图像列表
 * @param task_id
 * @returns
 */
export async function getResult(task_id: string, model: string) {
  const uri = '/image-generation/result';

  try {
    const res = await request.get(uri, {
      params: {
        model: model,
        task_id: task_id,
      },
    });

    const response = (res as unknown) as ApiResponse<TaskResult>;

    console.log('getResult 结果:', response)

    if (response.code !== 0) {
      message.error(response.message || '获取结果失败');
      return null;
    }

    if (response.data.output.task_status == 'FAILED') {
      message.error(response.data.message);
      return null;
    }
    if (response.data.output.task_status !== 'SUCCEEDED') {
      return [];
    }

    const results: Array<{ url: string }> = response.data.output.results.filter((item: any) => 'url' in item);
    const urls = results.map(item => item.url);
    return urls;
  } catch (error) {
    console.error('请求错误:', error);
    throw error;
  }

}


/**
 * 创建人像风格重绘任务
 * @param imageUrl
 * @param styleIndex
 */
export async function createPortraitStyleTask(image_url: string, style_index: number, style_ref_url?: string) {
  const uri = '/portrait-style-repaint/create/task';
  const payload = {
    model: 'wanx-style-repaint-v1',
    input: {
      image_url: image_url,
      style_index: style_index,
      style_ref_url: style_ref_url, // 如果有参考图片 URL，可以在这里添加
    },
  };

  const response = await request.post(uri, payload);
  return response.data.output.task_id;  // 直接返回 task_id
}




/**
 * 图像画面扩展
*/
export async function createOutpaintingTask(image_url: string, params: OutpaintingParams) {
  const uri = '/out-painting/create/task';

  const payload = {
    model: "image-out-painting",
    input: {
      image_url: image_url
    },
    parameters: params
  };

  try {
    const response = await request.post(uri, payload);
    return response.data.output.task_id;
  } catch (error) {
    console.error('创建扩图任务失败:', error);
    throw error;
  }
}